package io.eleKing.boot.weather.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.eleKing.boot.framework.exception.BusinessException;
import io.eleKing.boot.framework.page.OrderByItem;
import io.eleKing.boot.framework.page.OrderMapping;
import io.eleKing.boot.framework.page.Paging;
import io.eleKing.boot.weather.dto.WeatherStationDto;
import io.eleKing.boot.weather.entity.WeatherStation;
import io.eleKing.boot.weather.mapper.WeatherStationMapper;
import io.eleKing.boot.weather.query.WeatherStationQuery;
import io.eleKing.boot.weather.service.WeatherStationService;
import io.eleKing.boot.weather.vo.WeatherStationVo;
import io.eleKing.boot.util.PagingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;

/**
 * 自动站 服务实现类
 *
 * @author eleKing
 * @since 2025-04-15
 */
@Slf4j
@Service
public class WeatherStationServiceImpl extends ServiceImpl<WeatherStationMapper, WeatherStation> implements WeatherStationService {

    @Autowired
    private WeatherStationMapper weatherStationMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addWeatherStation(WeatherStationDto dto) {
        WeatherStation weatherStation = new WeatherStation();
        BeanUtils.copyProperties(dto, weatherStation);
        return save(weatherStation);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateWeatherStation(WeatherStationDto dto) {
        Long id = dto.getId();
        WeatherStation weatherStation = getById(id);
        if (weatherStation == null) {
            throw new BusinessException("自动站不存在");
        }
        BeanUtils.copyProperties(dto, weatherStation);
        return updateById(weatherStation);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteWeatherStation(Long id) {
        return removeById(id);
    }

    @Override
    public WeatherStationVo getWeatherStationById(Long id) {
        return weatherStationMapper.getWeatherStationById(id);
    }

    @Override
    public Paging<WeatherStationVo> getWeatherStationPage(WeatherStationQuery query) {
        OrderMapping orderMapping = new OrderMapping();
        orderMapping.put("createTime", "create_time");
        PagingUtil.handlePage(query, orderMapping, OrderByItem.desc("id"));
        List<WeatherStationVo> list = weatherStationMapper.getWeatherStationPage(query);
        Paging<WeatherStationVo> paging = new Paging<>(list);
        return paging;
    }

}
